import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import subprocess
import schedule
import time
import socket

hostname = socket.gethostname()
subject = f"{hostname} - 主机信息"
sender = "m18503090587@163.com"
license_code = "EQg93sCjETcqJbuz"
receivers = ["m18503090587@163.com"]

commands = ["ipconfig"]  # 支持多命令previous_output = {}
previous_output = {}

def send_email(subject, body, sender, license_code, receivers, smtp_host="smtp.163.com", smtp_port=465):
    try:
        mm = MIMEMultipart('related')
        mm["Subject"] = Header(subject, 'utf-8')
        mm["From"] = sender
        mm["To"] = ", ".join(receivers)

        message_text = MIMEText(body, "plain", "utf-8")
        mm.attach(message_text)

        stp = smtplib.SMTP_SSL(smtp_host, smtp_port)  # SSL加密连接
        stp.set_debuglevel(1)
        stp.login(sender, license_code)
        stp.sendmail(sender, receivers, mm.as_string())
        print("邮件发送成功")
        stp.quit()
    except Exception as e:
        print(f"发送邮件时发生错误: {e}")


def get_command_output(command):
    result = subprocess.run(
        command,
        shell=True,
        capture_output=True,
        text=True,
        encoding='gbk'  # 解决Windows中文乱码
    )
    return result.stdout.strip()


def check_commands():
    global previous_output
    current_output = {}
    for command in commands:
        output = get_command_output(command)
        current_output[command] = output

        if previous_output.get(command) != output:
            body = f"命令: {command}\n新输出:\n{output}"
            send_email(subject, body, sender, license_code, receivers)

    previous_output = current_output


#schedule.every(1).minutes.do(check_commands)

if __name__ == "__main__":
    while True:
       # schedule.run_pending()
        check_commands()
        time.sleep(1)